Boxing and Unboxing are essential concepts in C#. They form a link between a reference type and a value type.

Boxing and Unboxing is made possible because of the .Net framework common type system (CTS) which means that all types, reference and value, derive from the type object. It is possible to call methods on a value, such as 3.

Try it in the editor, type the numeral 3 followed by a full stop to invoke IntelliSense. Notice that there are various methods including Equals, GetHashCode, GetType and ToString. These are all inherited from the base CTS object.

Boxing is a process by which any value type (or reference type) can be treated as a reference type object and worked on before being unboxed back to its original value type.

int myInteger = 12345;

// myInteger is boxed
object Box = myInteger;

// myInteger is unboxed
int anotherInteger = (int)Box;

Why would you want to do this? Well suppose you need an array of objects that do not have the same type and need to iterate through them.

int a = 3;
decimal b = 4.35;
string c = "Hello";

object[] myList = new object[3];

// Box up the value and reference types together
myList[0] = a;
myList[1] = b;
myList[2] = c;

// Unbox the types
foreach (object Unboxed in myList)
{
  // Output the type of the object
  Console.WriteLine(Unboxed.GetType());

  if (typeof(Unboxed) == int)
  {
    // The object was an Int
  }
  else if (typeof(Unboxed) == string)
  {
    // The object was a string
  }
}

 

Tutorials in this Series